from rest_framework import serializers
from .models import DailyWorkProject, DailyWorkItem

class DailyWorkItemSerializer(serializers.ModelSerializer):
    """
    日工作计划工作项序列化器
    """
    responsible_list = serializers.SerializerMethodField()
    participants_list = serializers.SerializerMethodField()
    
    class Meta:
        model = DailyWorkItem
        fields = [
            'id',
            'content',
            'responsible',
            'participants',
            'responsible_list',
            'participants_list',
            'start_time',
            'end_time',
            'order',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_responsible_list(self, obj):
        """获取负责人列表"""
        return obj.get_responsible_list()
    
    def get_participants_list(self, obj):
        """获取执行人列表"""
        return obj.get_participants_list()

class DailyWorkProjectSerializer(serializers.ModelSerializer):
    """
    日工作计划项目序列化器
    """
    work_items = DailyWorkItemSerializer(many=True, read_only=True)
    duty_day_list = serializers.SerializerMethodField()
    duty_night_list = serializers.SerializerMethodField()
    
    class Meta:
        model = DailyWorkProject
        fields = [
            'id',
            'date',
            'experiment_type',
            'project_name',
            'duty_day',
            'duty_night',
            'duty_day_list',
            'duty_night_list',
            'work_items',
            'order',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_duty_day_list(self, obj):
        """获取日班值班人员列表"""
        return obj.get_duty_day_list()
    
    def get_duty_night_list(self, obj):
        """获取夜班值班人员列表"""
        return obj.get_duty_night_list()
    
    def validate_date(self, value):
        """
        验证日期格式
        """
        return value
    
    def validate_experiment_type(self, value):
        """
        验证实验类型
        """
        valid_types = [choice[0] for choice in DailyWorkProject.EXPERIMENT_TYPE_CHOICES]
        if value not in valid_types:
            raise serializers.ValidationError(f'实验类型必须是以下之一: {", ".join(valid_types)}')
        return value
    
    def update(self, instance, validated_data):
        """
        更新项目及其工作项
        """
        # 更新项目基本信息
        instance.date = validated_data.get('date', instance.date)
        instance.experiment_type = validated_data.get('experiment_type', instance.experiment_type)
        instance.project_name = validated_data.get('project_name', instance.project_name)
        instance.duty_day = validated_data.get('duty_day', instance.duty_day)
        instance.duty_night = validated_data.get('duty_night', instance.duty_night)
        instance.order = validated_data.get('order', instance.order)
        instance.save()
        
        # 处理工作项更新
        work_items_data = self.initial_data.get('work_items', [])
        if work_items_data:
            # 删除现有工作项
            instance.work_items.all().delete()
            
            # 创建新的工作项
            for i, work_item_data in enumerate(work_items_data):
                DailyWorkItem.objects.create(
                    project=instance,
                    content=work_item_data.get('content', ''),
                    responsible=work_item_data.get('responsible', ''),
                    participants=work_item_data.get('participants', ''),
                    start_time=work_item_data.get('start_time'),
                    end_time=work_item_data.get('end_time'),
                    order=work_item_data.get('order', i)
                )
        
        return instance

class DailyWorkPlanBulkSerializer(serializers.Serializer):
    """
    批量操作序列化器
    用于前端发送的项目数据结构
    """
    projects = serializers.ListField(
        child=serializers.DictField(),
        allow_empty=True
    )
    
    def validate_projects(self, value):
        """
        验证项目数据结构
        """
        for project_data in value:
            # 验证必需字段
            if 'date' not in project_data:
                raise serializers.ValidationError('每个项目必须包含日期字段')
            if 'experiment_type' not in project_data:
                raise serializers.ValidationError('每个项目必须包含实验类型字段')
            
            # 验证工作项
            work_items = project_data.get('workItems', [])
            if not isinstance(work_items, list):
                raise serializers.ValidationError('workItems必须是列表格式')
        
        return value
    
    def create(self, validated_data):
        """
        根据前端项目数据结构创建或更新记录
        """
        projects_data = validated_data['projects']
        created_projects = []
        
        # 收集所有涉及的日期和实验类型
        dates_and_types = set()
        for project_data in projects_data:
            dates_and_types.add((project_data['date'], project_data['experiment_type']))
        
        # 删除现有的相同日期和实验类型的项目（避免重复）
        for date, experiment_type in dates_and_types:
            DailyWorkProject.objects.filter(
                date=date,
                experiment_type=experiment_type
            ).delete()
        
        for project_data in projects_data:
            # 创建项目
            project = DailyWorkProject.objects.create(
                date=project_data['date'],
                experiment_type=project_data['experiment_type'],
                project_name=project_data.get('project', ''),
                duty_day=project_data.get('duty_day', ''),
                duty_night=project_data.get('duty_night', ''),
                order=project_data.get('order', 0)
            )
            
            # 创建工作项
            work_items_data = project_data.get('workItems', [])
            for i, work_item_data in enumerate(work_items_data):
                DailyWorkItem.objects.create(
                    project=project,
                    content=work_item_data.get('content', ''),
                    responsible=work_item_data.get('responsible', ''),
                    participants=work_item_data.get('participants', ''),
                    start_time=work_item_data.get('start_time'),
                    end_time=work_item_data.get('end_time'),
                    order=i
                )
            
            created_projects.append(project)
        
        return created_projects